package com.example.java10zookeeper_dubbo.zkdemo;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZookeeperDemo implements Watcher {

    private static CountDownLatch latch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws Exception {
        //连接Zookeeper
        zooKeeper = new ZooKeeper("192.168.223.166:2183",5000,new ZookeeperDemo());
        //阻塞线程
        latch.await();
        //读取数据
        byte[] data = zooKeeper.getData("/name", true, stat);
        System.out.println(new String(data));
        //阻塞主线程
        Thread.sleep(Integer.MAX_VALUE);
    }

    /**
     * 处理监听事件
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        //判断是否连接成功
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
            //判断是否连接但没有数据变化
            if(watchedEvent.getType() == Event.EventType.None && watchedEvent.getPath() == null){
                //结束线程阻塞
                latch.countDown();
            }else if(watchedEvent.getType() == Event.EventType.NodeDataChanged){
                //节点数据变化
                try {
                    System.out.println("发生修改：" + new String(zooKeeper.getData(watchedEvent.getPath(),true,stat)));
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
